import type { MenuDataItem, Settings as LayoutSettings } from '@ant-design/pro-layout';
import { SettingDrawer } from '@ant-design/pro-layout';
import { PageLoading } from '@ant-design/pro-layout';
import type { RunTimeLayoutConfig } from 'umi';
import { history, Link } from 'umi';
import RightContent from '@/components/RightContent';
import Footer from '@/components/Footer';
import { currentUser as queryCurrentUser } from './services/ant-design-pro/api';
import { BookOutlined, LinkOutlined } from '@ant-design/icons';
import defaultSettings from '../config/defaultSettings';

/*************** 2022/09/18 杜燕军 实现服务器加载自定义菜单 Add Start*******************/
// https://blog.csdn.net/renlimin1/article/details/126741986
import fixMenuItemIcon from './fixMenuItemIcon';
import { SmileOutlined, HeartOutlined } from '@ant-design/icons';
import { currentUserMenus as queryCurrentUserMenus } from './services/ant-design-pro/api';

const IconMap = {
  smile: <SmileOutlined />,
  heart: <HeartOutlined />,
};

const loopMenuItem = (menus: MenuDataItem[]): MenuDataItem[] =>
  menus.map(({ icon, routes, ...item }) => ({
    ...item,
    icon: icon && IconMap[icon as string],
    routes: routes && loopMenuItem(routes),
  }));

/*************** 2022/09/18 杜燕军 实现服务器加载自定义菜单 Add End*********************/

const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  loading?: boolean;
  /*************** 2022/09/18 杜燕军 实现服务器加载自定义菜单 Add Start*******************/
  menuData?: MenuDataItem[] | undefined;
  fetchUserMenus?: () => Promise<MenuDataItem[] | undefined>;
  /*************** 2022/09/18 杜燕军 实现服务器加载自定义菜单 Add End*********************/
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const msg = await queryCurrentUser();
      return msg.data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  /*************** 2022/09/18 杜燕军 实现服务器加载自定义菜单 Add Start*******************/
  const fetchUserMenus = async () => {
    try {
      const menuData = await queryCurrentUserMenus();
      return loopMenuItem(menuData.data);
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  /*************** 2022/09/18 杜燕军 实现服务器加载自定义菜单 Add End*********************/
  // 如果不是登录页面，执行
  if (history.location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    const currentUserMenus = await fetchUserMenus();
    return {
      fetchUserInfo,
      /*************** 2022/09/18 杜燕军 实现服务器加载自定义菜单 Add Start*******************/
      fetchUserMenus,
      menuData: currentUserMenus,
      /*************** 2022/09/18 杜燕军 实现服务器加载自定义菜单 Add End*********************/
      currentUser,
      settings: defaultSettings,
    };
  }
  return {
    fetchUserInfo,
    /*************** 2022/09/18 杜燕军 实现服务器加载自定义菜单 Add Start*******************/
    fetchUserMenus,
    menuData: [],
    /*************** 2022/09/18 杜燕军 实现服务器加载自定义菜单 Add End*********************/
    settings: defaultSettings,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  return {
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
      // 如果訪問頁面不在menuData中。重定向至404.防止在地址欄輸入路由名稱進入頁面
      /*
      if (initialState?.menuData?.length && location.pathname !== loginPath) {
        const isInMenu = initialState.menuData.find(item => item.path === location.pathname)
        if (!isInMenu) history.push('/404')
      }*/
    },
    links: isDev
      ? [
          <Link key="openapi" to="/umi/plugin/openapi" target="_blank">
            <LinkOutlined />
            <span>OpenAPI 文档</span>
          </Link>,
          <Link to="/~docs" key="docs">
            <BookOutlined />
            <span>业务组件文档</span>
          </Link>,
        ]
      : [],
    menuHeaderRender: undefined,
    /*************** 2022/09/18 杜燕军 实现服务器加载自定义菜单 Add Start*******************/
    menuDataRender: () => {
      return fixMenuItemIcon(initialState?.menuData);
    },
    /*************** 2022/09/18 杜燕军 实现服务器加载自定义菜单 Add End*********************/
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children, props) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        <>
          {children}
          {!props.location?.pathname?.includes('/login') && (
            <SettingDrawer
              disableUrlParams
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                setInitialState((preInitialState) => ({
                  ...preInitialState,
                  settings,
                }));
              }}
            />
          )}
        </>
      );
    },
    ...initialState?.settings,
  };
};
